import axios from 'axios';
import router from '../router';


// 将对象obj存入formData中
const setFormData = (params = {}) => {
  const formData = new FormData();
  Object.keys(params).forEach( key => {
    // let str = '';
    // if (typeof params[key] === "object") str = JSON.stringify(params[key]);
    // else if (!params[key]) str = '';
    // else str = params[key];
    formData.append(key, params[key]);
  });
  return formData;
  
};

const basic = ({ url, data, needLogin, file, fd }, method = 'post') => {
  const promise = new Promise((resolve, reject) => {
    // 网络请求
    if (fd) {
      file = true;
      data = setFormData(data);
    }
    const config = {
      baseURL: process.env.VUE_APP_BASE_API,
      url,
      data,
      params: data,
      method,
      headers: {
        'content-type': file ? 'multipart/form-data; boundary=ABCD' : 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      }
    };
    if (method === 'post' || method === 'put') {
      delete config.params;
    } else {
      delete config.body;
    }
    console.log(config);
    axios(config)
      .then(res => {
        // 服务器返回数据
        console.log(`${method} res------> ${url} ${JSON.stringify(data)}`, res);
        if (res.status === 200) {
          if (res.data && res.data.code === 200) {
            // resolve 只返回data
            // reject 只返回erroMsg
            resolve(res.data.response_data);
            // const err = check.error(res.data);
            // console.log("0", err)
          } else {
            reject({ message: res.data.message });
          }
        } else if (res.status === 401) {
          localStorage.setItem('token', '');
          // token.checkLogin(false);
          if (needLogin) {
            router.replace({
              path: '/login'
            });
          }
        } else if (res.status === 404) {
          reject({ message: '接口不存在 404' });
        } else if (res.status === 500) {
          reject({ message: '请稍后再试 500' });
        } else if (res.status === 503) {
          reject({ message: 'Service Unavailable 503' });
        } else {
          // 返回错误提示信息
          reject({ message: '网络错误' + res.status });
        }
      })
      .catch((res) => {
        console.log('http error');
        console.log('catch=>', res.response);
        if (res.response.status === 401) {
          // token.checkLogin(false);
          localStorage.setItem('token', '');
          if (needLogin) {
            router.replace({
              path: '/login'
            });
          }
        } else if (res.response.status === 404) {
          // 下单之后返回确认订单页，跳到购物车
          if (router.history.current.name === 'OrderConfirm') {
            router.replace({
              path: '/cart'
            });
            reject({ message: '您已下单请继续购物' });
          } else {
            reject({ message: '接口不存在 404' });
          }
        } else if (res.response.status === 500) {
          reject({ message: '请稍后再试 500' });
        } else if (res.response.status === 503) {
          reject({ message: 'Service Unavailable 503' });
        } else {
          // 返回错误提示信息
          reject({ message: '网络错误' + res.response.status });
        }
      });
  });
  return promise;
};
const post = ({ url = '/', data = {}, needLogin = true, file = false, fd = false }) => {
  return basic({ url, data, needLogin, file, fd }, 'post');
};
const get = ({ url = '/', data = {}, needLogin = true, file = false, fd = false }) => {
  return basic({ url, data, needLogin, file, fd }, 'get');
};
const put = ({ url = '/', data = {}, needLogin = true, file = false, fd = false }) => {
  return basic({ url, data, needLogin, file, fd }, 'put');
};
const del = ({ url = '/', data = {}, needLogin = true, file = false, fd = false }) => {
  return basic({ url, data, needLogin, file, fd }, 'delete');
};

export default {
  post,
  get,
  put,
  del
};
